package controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import Entity.CompanyType;
import Jdbcutil.MysqldataAccesshelper;

/**
 * Servlet implementation class CompanyController
 */
@WebServlet(name="CompanyController", urlPatterns= "/CompanyController")
public class CompanyController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String UPLOAD_DIRECTORY = "upload";
	private static final int THRESHOLD_SIZE 	= 1024 * 1024 * 3; 	// 3MB
	private static final int MAX_FILE_SIZE 		= 1024 * 1024 * 40; // 40MB
	private static final int MAX_REQUEST_SIZE 	= 1024 * 1024 * 50; // 50MB
	private static final String  filePathStored = "E:\\HKI-Nam III (2014-2015)\\CNPMM\\Workspace\\cnpmm-201409-11110226-11110177\\exercise\\final_project\\WebContent\\Images";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CompanyController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		List<CompanyType> listType = new ArrayList<CompanyType>();
		try {
			MysqldataAccesshelper helper = new MysqldataAccesshelper();
			helper.open();
			String sql = "select CompanyType,TypeName from companytype";
			ResultSet rs = helper.executeQuery(sql);
			CompanyType type;
			while (rs.next()) {
				type = new CompanyType();
				int companyType =rs.getInt("CompanyType");
				String text = rs.getString("TypeName");
				type.setValue(companyType);
				type.setText(text);
				listType.add(type);				
			}
			helper.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String result="";
		int n = listType.size();
		for(int i=0;i<n;i++){
			result+="<option value="+listType.get(i).getValue()+">"+listType.get(i).getText()+"</option>";
		}
		
		response.getWriter().write(result);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub	
		String companyName="";
		String address="";
		String phoneNumber="";
		String contactPerson="";
		String annualFinalcialReport=""; 
		String companyType="";
		String noOfWorkers="0";
		String noOfLine="0";
		String noOfMachines="0";
		String noOfBranches="0";
		String capacityOfProduct="0";
		String timeOfTextileMaterial="0";
		String timeOfTextileMaterialorigin="0" ;
		String sizeWorkShopImage="0";
		String sizeWareHouseImage = "0";
		List<String> listValueOfForm = new ArrayList<String>();
		List<String> listWarehouseImage = new ArrayList<String>();
		List<String> listWorkShopImage = new ArrayList<String>();
		// checks if the request actually contains upload file
				if (!ServletFileUpload.isMultipartContent(request)) {
					PrintWriter writer = response.getWriter();
					writer.println("Request does not contain upload data");
					writer.flush();
					return;
				}				
				
				// configures upload settings
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold(THRESHOLD_SIZE);
				factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
				
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setFileSizeMax(MAX_FILE_SIZE);
				upload.setSizeMax(MAX_REQUEST_SIZE);
				
				// constructs the directory path to store upload file
				String uploadPath = getServletContext().getRealPath("")
					+ File.separator + UPLOAD_DIRECTORY;
				// creates the directory if it does not exist
				File uploadDir = new File(uploadPath);
				if (!uploadDir.exists()) {
					uploadDir.mkdir();
				}
				
				try {
					// parses the request's content to extract file data
					List formItems = upload.parseRequest(request);
					Iterator iter = formItems.iterator();
					int i=0;
					// iterates over form's fields
					while (iter.hasNext()) {
						FileItem item = (FileItem) iter.next();
						if(item.isFormField()){
							String str = item.getString(); // lay gia tri cua all field trong form
							listValueOfForm.add(str);
						}
						// processes only fields that are not form fields
						else{
							if(!listValueOfForm.get(13).equals("")){
								sizeWorkShopImage = listValueOfForm.get(13);
							}
							if(!listValueOfForm.get(14).equals("")){
								sizeWorkShopImage = listValueOfForm.get(14);
							}
							String fileName = new File(item.getName()).getName();
							// lay sizeWork hinh dau tien luu cho workShopImage
							if(i< Integer.parseInt(sizeWorkShopImage)){
								listWorkShopImage.add(fileName);
								i++;
							}else{
							// lay sizeWare hinh tiep theo luu cho wareHouseImage
								listWarehouseImage.add(fileName);
								i++;
							}
							String filePath = filePathStored + File.separator + fileName;
							//String filePath = "D:\\" + File.separator + fileName;
							System.out.println(filePath);
							File storeFile = new File(filePath);
							
							// saves the file on disk
							item.write(storeFile);
						}
					}
					
				} catch (Exception ex) {
					ex.getMessage();
				}	
				//connect database
				try {
					
					companyName = listValueOfForm.get(0);					
					address  = listValueOfForm.get(1);
					phoneNumber = listValueOfForm.get(2);
					contactPerson  = listValueOfForm.get(3);
					annualFinalcialReport = listValueOfForm.get(4);
					companyType  = listValueOfForm.get(5);
					if(!listValueOfForm.get(6).equals("")){
						noOfWorkers =  listValueOfForm.get(6);
					}
					if(!listValueOfForm.get(7).equals("")){
						noOfLine = listValueOfForm.get(7);
					}
					if(!listValueOfForm.get(8).equals("")){
						noOfMachines  =listValueOfForm.get(8);
					}
					if(!listValueOfForm.get(9).equals("")){
						noOfBranches  = listValueOfForm.get(9);
					}
					if(!listValueOfForm.get(10).equals("")){
						capacityOfProduct  = listValueOfForm.get(10);
					}
					if(!listValueOfForm.get(11).equals("")){
						timeOfTextileMaterial =listValueOfForm.get(11);
					}
					if(!listValueOfForm.get(12).equals("")){
						timeOfTextileMaterialorigin =listValueOfForm.get(12);
					}
					
					int i  = listWorkShopImage.size();
					int j = listWarehouseImage.size();
					
					String GroupWorkShopImages = companyName+"A";
					String GroupWareHouseImages = companyName+"B";
					
					MysqldataAccesshelper helper = new MysqldataAccesshelper();
					helper.open();
					
					//cac cong viec 
					// 1. luu groupimages
					String sql1 = String.format("insert into groupimage (GroupName)values('%s')",GroupWorkShopImages );
					String sql2 = String.format("insert into groupimage (GroupName)values('%s')", GroupWareHouseImages);
					helper.executeUpdate(sql1);
					helper.executeUpdate(sql2);
					// 2. Luu images
					// 2.1 Lay Id cua group
					String sql3 =String.format( "select GroupID from groupimage where GroupName= '%s'",GroupWorkShopImages);
					String sql4 =String.format( "select GroupID from groupimage where GroupName= '%s'",GroupWareHouseImages);
					ResultSet rs= helper.executeQuery(sql3);
					int groupWorkShopID=0; // 						
					while (rs.next()) {
						groupWorkShopID = rs.getInt("GroupID"); 
					}
					ResultSet rs1= helper.executeQuery(sql4);
					int groupWareHouseID=0; // 						
					while (rs1.next()) {
						groupWareHouseID = rs1.getInt("GroupID"); 
					}
					// 2.2 luu tung hinh
					for(int k=0;k<listWorkShopImage.size();k++){
						
						String path = listWorkShopImage.get(k);
						String sql5 = String.format("insert into image (ImagePath,GroupID) values ('%s',%d)",path,groupWorkShopID);
						helper.executeUpdate(sql5);
					}
					for(int k=0;k<listWarehouseImage.size();k++){						
						String path = listWarehouseImage.get(k);
						String sql5 = String.format("insert into image (ImagePath,GroupID) values ('%s',%d)",path,groupWareHouseID);
						helper.executeUpdate(sql5);
					}
					// 3. luu company
					String sql=String.format("insert into company (CompanyName,Address,PhoneNumber,ContactPerson,FinancialReport,"
							+ "CompanyType,NoWorkers,NoLines,NoMachinesLine,NoBranches,CapacityOfDayMonth,TimeTextile,TimeTextileOrigin,WorkshopImage,WarehouseImage)"
							+ "	values('%s','%s','%s','%s','%s','%d','%d','%d','%d','%d','%f','%f','%f',%d,%d)"
							,companyName,address,phoneNumber,contactPerson,annualFinalcialReport,Integer.parseInt(companyType)
							,Integer.parseInt(noOfWorkers),Integer.parseInt(noOfLine),Integer.parseInt(noOfMachines),Integer.parseInt(noOfBranches),Float.parseFloat(capacityOfProduct),Float.parseFloat(timeOfTextileMaterial),Float.parseFloat(timeOfTextileMaterialorigin),groupWorkShopID,groupWareHouseID);
					helper.executeUpdate(sql);
					helper.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
	}

}
